'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 查询BOSS伤害排行
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var moment = require('moment');
var async = require('async');
var Code = require('../../../../consts/code');
var unionBossModel = require('../../../../models/unionBossModel.js');
var PlayerManager = require('../../../../libs/playerManager.js');

/**
 * 查询BOSS伤害排行
 */
module.exports = function (msg, session, next) {
    var role_id = session.uid;

    var damage_rank;
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['role'], cb);
            },
            function (cb) {
                var union_id = player_manager.role.union_id;
                if (union_id === 0) {
                    return next(null, {
                        code: Code.UNION_IS_NOT_JOIN
                    });
                }

                // 查询联盟BOSS信息
                unionBossModel.findById(union_id, cb);
            },
            function (model, cb) {
                var union_boss_model = model;
                var damage_list = union_boss_model.damage_list;
                _getWithRoleInfo(damage_list, cb);
            },
            function (list, cb) {
                damage_rank = _.orderBy(list, ['damage'], ['desc']);
                var rank = 0;
                _.forEach(damage_rank, function (item) {
                    rank++;
                    item.rank = rank;
                });
                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    damage_rank: damage_rank
                }
            });
        }
    );
};

/**
 * 查询角色相关信息
 * @return {[type]} [description]
 */
var _getWithRoleInfo = function (damage_list, cb) {
    var rank_list = [];
    async.eachSeries(damage_list, function (dmg, callback) {
        var player_manager = new PlayerManager(dmg.role_id);
        player_manager.getModel(['role'], function (err) {
            if (!!err) {
                return cb(err, []);
            }
            var role_model = player_manager.role;
            rank_list.push({
                role_id: role_model.role_id,
                name: role_model.name,
                job_type: role_model.job_type,
                lv: role_model.lv,
                damage: dmg.damage,
                last_modify_tm: dmg.last_modify_tm
            });
            callback();
        });
    }, function (err) {
        if (!!err) {
            return cb(err, []);
        }
        return cb(null, rank_list);
    });
};
